package encryption;


import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class Encryption {

	private String keyString = "The Super Secret Password";
	private SecretKeySpec key;
	private Cipher cipher;
	private boolean cipherSuccess;
	public Encryption(){
		
		//byte[] keyBytes = keyString.getBytes();
		//keyBytes = Arrays.copyOf(keyBytes, 128);//pads array with zeroes or truncates as necessary
		//key = new SecretKeySpec(keyBytes, "AES");
		
		char[] keyChars = new char[keyString.length()];
		keyString.getChars(0, keyString.length(), keyChars, 0);
		
		try {
			SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
			KeySpec spec = new PBEKeySpec(keyChars, new byte[]{}, 1024, 128);
			SecretKey tmp = factory.generateSecret(spec);
			key = new SecretKeySpec(tmp.getEncoded(), "AES");
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (InvalidKeySpecException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		cipherSuccess = false;
		try {
			cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipherSuccess = true;
		} catch (NoSuchAlgorithmException e) {
			cipherSuccess = false;
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			cipherSuccess = false;
			e.printStackTrace();
		}

	}

	public byte[] encrypt (byte[] decrypted) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
		//encrypts bytes 
		if (cipherSuccess){
			cipher.init(Cipher.ENCRYPT_MODE, key);
			return cipher.doFinal(decrypted);
		}
		return new byte[]{};
	}
	public byte[] decrypt (byte[] encrypted) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
		//decrypts bytes
		if(cipherSuccess){
			cipher.init(Cipher.DECRYPT_MODE, key);
			return cipher.doFinal(encrypted);
		}
		return new byte[]{};
	}


}

